#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDataStream>
#include <qsqlquerymodel.h>
#include "dialog.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QString ipv4addr = "";
    const QHostAddress &localhost = QHostAddress(QHostAddress::LocalHost);
    for (const QHostAddress &address: QNetworkInterface::allAddresses())
    {
        if (address.protocol() == QAbstractSocket::IPv4Protocol && address != localhost)
            ipv4addr += " - " + address.toString();
    }
    this->setWindowTitle("ИСAП-сервер" + ipv4addr);
    settings = new QSettings(ORGANIZATION_NAME, APPLICATION_NAME);
    myTcpServer = new ServerTCP();
    sqlReguest = new SqlRequest(); //Запросы к базе данных
    sqlReguest->connectDB();
    myTcpServer->startServer(); //Запсукаем сервер для обмена сокетами
    ekran = new ekran_ocen(); //Подключаем экран
    ekranFlag = new ekran_flag(); //Подключаем экран
    //Добавляем сочетание клавиш для настойки сервера
    keyCtrlS = new QShortcut(this);
    keyCtrlS->setKey(Qt::CTRL + Qt::Key_S);
    connect(keyCtrlS, SIGNAL(activated()), this, SLOT(slotShortcutCtrlS()));

    keyCtrlJ = new QShortcut(this);
    keyCtrlJ->setKey(Qt::CTRL + Qt::Key_J);
    connect(keyCtrlJ, SIGNAL(activated()), this, SLOT(slotShortcutCtrlJ()));

    connect(myTcpServer, SIGNAL(connect_judges(int)), this, SLOT(connectJudges(int))); //При подключении пульта к серверу создаём ComboBox с данными
    connect(myTcpServer, SIGNAL(sig_dickconnect(int)), this, SLOT(diskonectJudges(int))); //При отключении пульта
    connect(myTcpServer, SIGNAL(perfomance_judges(QJsonObject)), this, SLOT(perfomanceJudges(QJsonObject))); //Судья подключился и готов судить
    connect(myTcpServer, SIGNAL(read_ocenki()), this, SLOT(readOcenki())); //Судья подключился и готов судить
    connect(myTcpServer, SIGNAL(connect_timekeeper(int)), this, SLOT(connectTimekeeper(int))); //Судья подключился и готов судить
    connect(myTcpServer, SIGNAL(connect_participants(int)), this, SLOT(connectParticipants(int))); //Судья подключился и готов судить
    connect(myTcpServer, SIGNAL(start_stop_timer()), this, SLOT(on_btnTimer_clicked())); //Судья подключился и готов судить
    connect(myTcpServer, SIGNAL(start_stop_timer()), ekran, SLOT(startTimer()));

    connect(this, SIGNAL(connectDevice(QJsonObject)), myTcpServer, SLOT(SendToDevice(QJsonObject))); //Отправляем для номер судьи для терминала
    connect(this, SIGNAL(startPerfomance(QJsonObject)), myTcpServer, SLOT(SendToCLient(QJsonObject))); //Отпрвляем на терминал выступления которое будут судить
    connect(this, SIGNAL(connectCountJudges(QJsonObject)), myTcpServer, SLOT(SendToCLient(QJsonObject))); //Отпрвляем на терминал информацию что судьи подключены
    connect(this, SIGNAL(ocenkiSelect(QJsonObject)), myTcpServer, SLOT(SendToCLient(QJsonObject))); //Отпрвляем на терминал оценки для вывода
    connect(this, SIGNAL(stopVistup(QJsonObject)), myTcpServer, SLOT(SendToCLient(QJsonObject))); //Оставнавливаем выступление
    connect(this, SIGNAL(deleteGradesJudges(QJsonObject)), myTcpServer, SLOT(SendToCLient(QJsonObject))); //Удаление оценки судьи
    connect(this, SIGNAL(waitPerfomance(QJsonObject)), myTcpServer, SLOT(SendToCLient(QJsonObject))); //Отпрвляем на терминал выступления которое будут судить
    connect(this, SIGNAL(reconnectDevice(QJsonObject)), myTcpServer, SLOT(SendToDevice(QJsonObject)));
    connect(this, SIGNAL(participantsDevice(QJsonObject)), myTcpServer, SLOT(SendToDevice(QJsonObject)));

    connect(ui->ekran, SIGNAL(clicked()), ekran, SLOT(show()));
    connect(ui->btn03, SIGNAL(clicked()), ekran, SLOT(minusPerfomance())); //Открываем экран для демонстрации оценок
    connect(this, SIGNAL(sendDataSys(QJsonObject,int)), ekran, SLOT(recieveDataSys(QJsonObject,int))); //Отправляем данные для вывода кто выступает и какие пхумсэ выполняются
    connect(ui->btnTimer, SIGNAL(clicked()), ekran, SLOT(startTimer()));
    connect(this, SIGNAL(sendJudgesOcen(QJsonObject)), ekran, SLOT(showJudgesOcen(QJsonObject))); //Отправляем кто из судей выставил оценки
    connect(this, SIGNAL(sendOcenSys(QJsonObject)), ekran, SLOT(recieveOcenSys(QJsonObject))); //Отправляем оценки
    connect(this, SIGNAL(readRange()), ekran, SLOT(range())); //Вывод ранга

    connect(ui->ekranFlags, SIGNAL(clicked()), ekranFlag, SLOT(show()));
    connect(this, SIGNAL(sendDataFlags(QJsonObject)), ekranFlag, SLOT(recieveDataFlag(QJsonObject)));
    connect(this, SIGNAL(sendOcenFlags(QJsonObject)), ekranFlag, SLOT(recieveOcenFlag(QJsonObject))); //Отправляем оценки

    ui->tabWidget->setCurrentIndex(0);

    ui->tabWidget->setProperty("styleclass", "tabwidget"); //Убираем вкладки
    if(settings->value("SETTINGS_KSUD").toInt() != 0) {
        switch (settings->value("SETTINGS_SYST").toInt()) {
        case 1:
        case 2:
            ui->tabWidget->setCurrentIndex(1);
            loadViewCutFreestyle();
            break;
        default:
            ui->tabWidget->setCurrentIndex(2);
            flagsLoadView();
            break;
        }
    }
    ui->lTimerPerfomance->hide();
    ui->start->setEnabled(true);
//    ui->ekran->setEnabled(true);
    ui->startFlags->setEnabled(true);
    ui->stopBtn->setEnabled(false);
    ui->btnTimer->setEnabled(false);
}

MainWindow::~MainWindow()
{
    delete ui;
}

//Настройки сервера
void MainWindow::on_send_clicked()
{
    QButtonGroup kort;
    QButtonGroup kol_sud;
    QButtonGroup sys;
    QList<QRadioButton *> allKortButtons = ui->kort_num->findChildren<QRadioButton *>();
    QList<QRadioButton *> allSysButtons = ui->sys->findChildren<QRadioButton *>();
    QList<QRadioButton *> allSudButtons = ui->kol_sud->findChildren<QRadioButton *>();
    for(int i = 0; i < allKortButtons.size(); ++i)
    {
        kort.addButton(allKortButtons[i],i);
    }
    for(int i = 0; i < allSysButtons.size(); ++i)
    {
        sys.addButton(allSysButtons[i],i);
    }

    for(int i = 0; i < allSudButtons.size(); ++i)
    {
        kol_sud.addButton(allSudButtons[i],i);
    }
    judgesClick = kol_sud.checkedId()+1;
    kortClick = kort.checkedId()+1;
    sysClick = sys.checkedId()+1;
    switch (judgesClick) {
        case 1: countJudges = 1;
            break;
        case 2: countJudges = 3;
            break;
        case 3: countJudges = 5;
            break;
        case 4: countJudges = 7;
            break;
    }
    settings->setValue("SETTINGS_KORT", kortClick);
    settings->setValue("SETTINGS_SYST", sysClick);
    settings->setValue("SETTINGS_KSUD", countJudges);
    if (judgesClick != 0 and sysClick != 0 and kortClick != 0) {
        addBase();
    } else {
        proverka();
    }
}

//Проверка что все данные выбраны
void MainWindow::proverka() {
    if (kortClick == 0) {
        QMessageBox::information(this, tr("Court"), tr("Корт не выбран"));
    }
    if (sysClick == 0) {
        QMessageBox::information(this, tr("Система"), tr("Система не выбрана"));
    }
    if (countJudges == 0) {
        QMessageBox::information(this, tr("Количество судей"), tr("Количество судей не выбрано"));
    }
}

//Добавление или обновление настроек для сервера
void MainWindow::addBase() {
    QMap<QString,QString> setting;
    setting["court"] = QString::number(settings->value("SETTINGS_KORT").toInt());
    setting["system"] = QString::number(settings->value("SETTINGS_SYST").toInt());
    setting["countJudges"] = QString::number(settings->value("SETTINGS_KSUD").toInt());
    if(sqlReguest->settingsAdd(setting) != 0) {
        QMessageBox::information(this, tr("Setting"), tr("Настройки сохранены или обновлены"));
        switch (settings->value("SETTINGS_SYST").toInt()) {
        case 1:
        case 2:
            ui->tabWidget->setCurrentIndex(1);
            loadViewCutFreestyle();
            break;
        default:
            ui->tabWidget->setCurrentIndex(2);
            flagsLoadView();
            break;
        }
    } else {
        QMessageBox::information(this, tr("Setting"), tr("Ошибам при сохранении настроек"));
    }
}

//Загрузка сервера
void MainWindow::loadViewCutFreestyle() {
    tableWidget = new QTableWidget(this);
    tableWidgetEnd = new QTableWidget(this);
    comboBox = new QComboBox(this);
    values = new QList<QPair<int,QString>>();
    model = new QComboBoxModel();
    groupsBtn[0].bvline = ui->button_judges;
    groupsBtn[0].bvline->addWidget(comboBox);
    groupsBtn[1].bhline = ui->del_button;
    groupsGrades[0] = ui->first_accurasy;
    groupsGrades[1] = ui->first_presentation;
    groupsGrades[2] = ui->second_accurasy;
    groupsGrades[3] = ui->second_presentation;
    comboBox->hide();
    for(int i=0; i<2; i++) {
        groupsBtn[i].bgroup = new QButtonGroup(this);
        groupsBtn[i].bgroup->setProperty("lineNumber", i);
        connect(groupsBtn[i].bgroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(onButtonClicked(QAbstractButton*)));
    }
    for(int i=0; i<4; i++)
    {
        for(int j=0; j<settings->value("SETTINGS_KSUD").toInt(); j++)
        {
            lscore[i][j] = new QLineEdit();
            lscore[i][j]->setText("0.0");
            lscore[i][j]->setObjectName("grades");
            lscore[i][j]->setAlignment(Qt::AlignCenter);
            groupsGrades[i]->addWidget(lscore[i][j]);
            if(i==0) {
                btn[i][j] = new QPushButton();
                btn[i][j]->setText(tr("Judges №") + QString::number(j+1));
                btn[i][j]->setProperty("styleclass", "judgesbtn");
                btn[i][j]->setProperty("value", j+1);
                btn[i][j]->setProperty("click", 0);
                groupsBtn[i].bvline->addWidget(btn[i][j]);
                groupsBtn[i].bgroup->addButton(btn[i][j]);
                groupsBtn[i].bvline->setEnabled(false);
            }
            if(i==1) {
                btn[i][j] = new QPushButton();
                btn[i][j]->setText("X");
                btn[i][j]->setProperty("styleclass", "btndel");
                btn[i][j]->setProperty("value", j+1);
                groupsBtn[i].bhline->addStretch();
                groupsBtn[i].bhline->addWidget(btn[i][j]);
                groupsBtn[i].bhline->addStretch();
                groupsBtn[i].bgroup->addButton(btn[i][j]);
            }
        }
    }
    if(QApplication::screens().size() > 1) {
        QScreen* screen = QApplication::screens().at(1);
        QSize size = screen->availableSize();
        if (size.width() == 1920 && size.height() > 1000) {
            ui->ekran->setEnabled(true);
        }
    }
//    connect(tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(doSomething(int,int)));
    loadTablePerfomance();
    loadViewSettingsServer();
    loadCategories();
    ui->start->setToolTip("Подключите всех судей");
    ui->ekran->setToolTip("Должен быть подлючен второй экран разрешением 1920х1080");
    ui->start->statusTip();
    ui->ekran->statusTip();
}

//Нажатие на кноку судьи, чтобы назначить номер судьи пульту
void MainWindow::onButtonClicked(QAbstractButton *button) {
    QJsonObject obj;
    QJsonObject objDevice;
    QJsonObject delObjGradesJudges;
    QMap<QString,int> judges;
    int lineNumber = button->group()->property("lineNumber").toInt();

    switch (lineNumber) {
    case 0:
        if(comboBox->currentIndex() != -1 && lineNumber == 0 && button->property("click").toInt() == 0) {
            groupsBtn[lineNumber].value = button->property("value").toInt();
            judges["numberJudges"] = groupsBtn[lineNumber].value;
            judges["kort"] = settings->value("SETTINGS_KORT").toInt();
            judges["socket"] = devices[(*this->values)[comboBox->currentIndex()].second];
            sqlReguest->updateDevice(judges);
            button->setText(tr("Judges ") + QString::number(groupsBtn[lineNumber].value) + "\n" + (*this->values)[comboBox->currentIndex()].second);
            obj["command"] = 0;
            obj["nomersud"] = groupsBtn[lineNumber].value;
            obj["socket"] = devices[(*this->values)[comboBox->currentIndex()].second];
            if(startInt == 0) emit connectDevice(obj);
            if(comboBox->currentIndex() != -1) model->deleteRow(comboBox->currentIndex());
            if(comboBox->count() == 0) comboBox->hide();
            if (sqlReguest->countJudges(settings->value("SETTINGS_KORT").toInt()) == settings->value("SETTINGS_KSUD").toInt() && startInt == 0) ui->start->setEnabled(true);
            button->setEnabled(false);
            button->setStyleSheet("background-color:green");
            button->setProperty("click", 1);
            if (startInt == 1) {
                objDevice = sqlReguest->startVistup(settings->value("SETTINGS_SYST").toInt());
                objDevice["countJudges"] = settings->value("SETTINGS_KSUD").toInt();
                objDevice["socket"] = obj["socket"];
                objDevice["command"] = 7;
                objDevice["nomersud"] = groupsBtn[lineNumber].value;
                emit reconnectDevice(objDevice);
                for(int j=0; j<settings->value("SETTINGS_KSUD").toInt(); j++) btn[0][j]->setEnabled(false);
            }
        } else {
            button->setStyleSheet("background-color:red");
            button->setProperty("click", 0);
            button->setText(tr("Judges №") + QString::number(button->property("value").toInt()));
        }
        break;
    case 1:
        if(startInt == 1) {
            groupsBtn[lineNumber].value = button->property("value").toInt();
            delObjGradesJudges["command"] = 5;
            delObjGradesJudges["idvitup"] = idperfomance;
            delObjGradesJudges["delNomerSud"] = groupsBtn[lineNumber].value;
            lscore[countVistup][groupsBtn[lineNumber].value-1]->setReadOnly(true);
            lscore[countVistup+1][groupsBtn[lineNumber].value-1]->setReadOnly(true);
            lscore[countVistup][groupsBtn[lineNumber].value-1]->setText("0.0");
            lscore[countVistup+1][groupsBtn[lineNumber].value-1]->setText("0.0");
            sqlReguest->delOcenki(delObjGradesJudges);
            emit deleteGradesJudges(delObjGradesJudges);
        }
        break;
    }
}

void MainWindow::slotShortcutCtrlS()
{
    switch (settings->value("SETTINGS_SYST").toInt()) {
    case 1:
    case 2:
        for(int j=0; j<4; j++)
        {
            for(int i=0; i<settings->value("SETTINGS_KSUD").toInt(); i++)
            {
                lscore[j][i]->deleteLater();
                if(j==0) {
                    btn[j][i]->deleteLater();
                }
                if(j==1) {
                    btn[j][i]->deleteLater();
                }
            }
        }
        tableWidget->deleteLater();
        tableWidgetEnd->deleteLater();
        break;
    default:
        for(int i=0; i<settings->value("SETTINGS_KSUD").toInt(); i++)
        {
            btn[0][i]->deleteLater();
            btnFlags[i]->deleteLater();
        }
        break;
    }
    comboBox->deleteLater();
    settings->setValue("SETTINGS_KSUD", 0);
    ui->tabWidget->setCurrentIndex(0);
    loadTable = 0;
}

void MainWindow::slotShortcutCtrlJ()
{
    for(int j=0; j<settings->value("SETTINGS_KSUD").toInt(); j++)
    {
        btn[0][j]->setEnabled(true);
    }
}

//Подключаем устройства и назначаем им номер судьи
void MainWindow::connectJudges(int idDevice) {
    QJsonObject deviceObject = sqlReguest->deviceSelect(idDevice);
    deviceName = deviceObject.value("device_name").toString();
    deviceSocket = deviceObject.value("device_socketConn").toInt();
    devices[deviceName] = deviceSocket;
    createComboBox();
}

//Подключаем устройства и назначаем им номер судьи
void MainWindow::connectTimekeeper(int idDevice) {
    QJsonObject deviceObject = sqlReguest->deviceSelect(idDevice);
    deviceSocketTimekeeper = deviceObject.value("device_socketConn").toInt();
}

//Подключаем устройства и назначаем им номер судьи
void MainWindow::connectParticipants(int idDevice) {
    QJsonObject deviceObject = sqlReguest->deviceSelect(idDevice);
    deviceSocketParticipants = deviceObject.value("device_socketConn").toInt();
}

//Отключение судей от сервера
void MainWindow::diskonectJudges(int numSud) {
    if(numSud != 0) {
        btn[0][numSud-1]->setStyleSheet("background-color:red");
        btn[0][numSud-1]->setText(tr("Judges № ") + QString::number(numSud));
        btn[0][numSud-1]->setEnabled(true);
        btn[0][numSud-1]->setProperty("click", 0);
    }
}

//Создаём список устройств для подключения судей
void MainWindow::createComboBox() {
    if (comboBox->findText(deviceName) != -1) model->deleteRow(comboBox->findText(deviceName));
    comboBox->show();
    groupsBtn[0].bvline->setEnabled(true);
    comboBox->addItem(deviceName);
    values->append(QPair<int,QString>(deviceSocket, deviceName));
    model->populate(values);
    comboBox->setModel(model);
}

//Запуск выступления
void MainWindow::on_start_clicked()
{
    countGrades = 0;
    countConnectJudges = 0;
    minus03 = 0;
    startInt = 1;
    ui->lMinus03->setText(QString::number(minus03));
    QJsonObject obj = sqlReguest->startVistup(settings->value("SETTINGS_SYST").toInt());
    if(obj.count() > 0) {
        loadTablePerfomance();
        loadTablePerfomanceEnd();
        ui->start->setEnabled(false);
        ui->stopBtn->setEnabled(true);
        ui->btnTimer->setEnabled(true);
        obj["countJudges"] = settings->value("SETTINGS_KSUD").toInt();
        obj["command"] = 1;
        emit startPerfomance(obj);
        pokazPhumse = obj["pokaz"].toInt();
        idperfomance = obj["idvist"].toInt();
        kategoria = obj["kategoria"].toString();
        nomer = obj["nomer"].toInt();
        krugNomer = obj["krugNomer"].toInt();
        sportsmen = obj["sportsmen"].toString();
        countVistup = obj["countVistup"].toInt();
        if(obj["idvistpred"].toInt() != 0 && totalVistup[pokazPhumse-1] == 0) {
            idvistpred = obj["idvistpred"].toInt();
            readOcenkiPred();
        }
        if (pokazPhumse == 1) {
            kolPhum = sqlReguest->kolPhumKatek(obj);
            ui->total1->setStyleSheet("color:red");
            ui->total2->setStyleSheet("color:red");
            ui->total->setStyleSheet("color:red");
        }
        for (int i = 0; i < settings->value("SETTINGS_KSUD").toInt(); i++) {
            lscore[countVistup][i]->setEnabled(false);
            lscore[countVistup+1][i]->setEnabled(false);
        }
        for(int j = 0; j<10; j++) {
            tableWidget->item(0,j)->setBackground(Qt::red);
            tableWidgetEnd->item(0,j)->setBackground(Qt::red);
        }
//        if(deviceSocketParticipants != 0) {
//            sendParticipants();
//        }
        emit sendDataSys(obj, kolPhum);
        readOcenki();
    }
}

void MainWindow::sendParticipants() {
//    QJsonObject objParticipants = sqlReguest->selectParticipants(kategoria, krugNomer);
    QJsonObject objParticipants = sqlReguest->tablServerVist();
    objParticipants["command"] = 30;
    objParticipants["socket"] = deviceSocketParticipants;
    emit participantsDevice(objParticipants);
}

//Какие судьи готовы судить выступление
void MainWindow::perfomanceJudges(QJsonObject obj)
{
    QJsonValue jv;
    QJsonArray ja;
    QJsonObject subtree;
    QJsonObject countJudges;
    countConnectJudges += 1;
    switch (settings->value("SETTINGS_SYST").toInt()) {
    case 1:
    case 2:
        for (int i=0; i<obj.count(); i++) {
            jv = obj.value("judges"+QString::number(i));
            if(jv.isArray()) {
                ja = jv.toArray();
                subtree = ja.at(0).toObject();
                lscore[countVistup][subtree["nomersud"].toInt()-1]->setReadOnly(true);
                lscore[countVistup+1][subtree["nomersud"].toInt()-1]->setReadOnly(true);
            }
        }
        break;
    default:
        ui->lFlagsBlue->setStyleSheet("background-color: rgb(0, 87, 255); color: green;");
        ui->lFlagsRed->setStyleSheet("background-color: rgb(255, 24, 0); color: green");
        break;
    }
    if(countConnectJudges == settings->value("SETTINGS_KSUD").toInt() || sqlReguest->countJudgesPerfomance(idperfomance) == settings->value("SETTINGS_KSUD").toInt()) {
        countJudges["command"] = 2;
        emit connectCountJudges(countJudges);
    }
}

//Оценки судей кто выставил
void MainWindow::readOcenki() {
    QJsonObject jsonOcenki = sqlReguest->ocenkiSelect(idperfomance);
    QJsonValue jv;
    QJsonArray ja;
    QJsonObject subtree;
    jv = jsonOcenki.value("ocenki");
    if(jv.isArray()) {
        ja = jv.toArray();
        for(int i=0; i<ja.count(); i++) {
            subtree = ja.at(i).toObject();
            switch (settings->value("SETTINGS_SYST").toInt()) {
            case 1:
            case 2:
                lscore[countVistup][subtree["ocenki_nomsud"].toInt()-1]->setText(QString::number(subtree["ocenki_t"].toDouble()/10, 'f', 1));
                lscore[countVistup+1][subtree["ocenki_nomsud"].toInt()-1]->setText(QString::number(subtree["ocenki_p"].toDouble()/10, 'f', 1));
                lscore[countVistup+1][subtree["ocenki_nomsud"].toInt()-1]->setEnabled(true);
                lscore[countVistup][subtree["ocenki_nomsud"].toInt()-1]->setEnabled(true);
                break;
            default:
                ui->lFlagsBlue->setStyleSheet("background-color: rgb(0, 87, 255); color: yellow;");
                ui->lFlagsRed->setStyleSheet("background-color: rgb(255, 24, 0); color: yellow");
                break;
            }
        }
    }
    emit ocenkiSelect(jsonOcenki);
    emit sendJudgesOcen(jsonOcenki);
    if(jsonOcenki["ocenkiCount"].toInt() == settings->value("SETTINGS_KSUD").toInt()) {
        tmrInt = 1;
        startAutoTimer();
        ui->prinat->setEnabled(true);
        ui->btn03->setEnabled(true);
        sumOcenki();
    }
}

//Оценки судей кто выставил
void MainWindow::readOcenkiPred() {
    QJsonObject jsonOcenki = sqlReguest->ocenkiSelect(idvistpred);
    QJsonValue jv;
    QJsonArray ja;
    QJsonObject subtree;
    for (int i=0; i<jsonOcenki.count(); i++) {
        jv = jsonOcenki.value("ocenki"+QString::number(i));
        if(jv.isArray()) {
            ja = jv.toArray();
            subtree = ja.at(0).toObject();
            switch (settings->value("SETTINGS_SYST").toInt()) {
            case 1:
            case 2:
                lscore[countVistup-2][subtree["ocenki_nomsud"].toInt()-1]->setText(QString::number(subtree["ocenki_t"].toDouble()/10, 'f', 1));
                lscore[countVistup-1][subtree["ocenki_nomsud"].toInt()-1]->setText(QString::number(subtree["ocenki_p"].toDouble()/10, 'f', 1));
                break;
            default:
                ui->lFlagsBlue->setStyleSheet("background-color: rgb(0, 87, 255); color: yellow;");
                ui->lFlagsRed->setStyleSheet("background-color: rgb(255, 24, 0); color: yellow");
                break;
            }
        }
    }
    if(jsonOcenki["ocenkiCount"].toInt() == settings->value("SETTINGS_KSUD").toInt()) {
        sumOcenki();
    }
}

//Считаем итоговую оценку за выступление
void MainWindow::sumOcenki() {
    switch (settings->value("SETTINGS_SYST").toInt()) {
    case 1:
    case 2: {
            QJsonObject totalObject = sqlReguest->total();

            tempCalc = totalObject["sumAccuracy"].toInt() + totalObject["sumPresentation"].toInt();
            sumAccuracyObsh = totalObject["sumAccuracy"].toInt();
            sumPresentationObsh = totalObject["sumPresentation"].toInt();
            totalSum[pokazPhumse] = sumAccuracyObsh + sumPresentationObsh;
            int judCount = settings->value("SETTINGS_KSUD").toInt();
            if(settings->value("SETTINGS_KSUD").toInt() > 3)
            {
                tempCalc = tempCalc - totalObject["accuracyMinMax"].toInt() - totalObject["presentationMinMax"].toInt();
                sumPresentationObsh = sumPresentationObsh - totalObject["presentationMinMax"].toInt();
                judCount -= 2;
            }

            tempCalc = 100 * tempCalc / judCount;
            sumPresentationObsh = 100 * sumPresentationObsh / judCount;
            if(tempCalc % 10 == 5)
            {
                tempCalc /= 10;
                tempCalc += tempCalc % 2;
            }
            else
                tempCalc = qRound(tempCalc / 10.0);
            if(idvistpred != 0 && totalVistup[pokazPhumse-1] == 0) {
                totalSum[pokazPhumse-1] = sumAccuracyObsh + sumPresentationObsh;
                totalVistup[pokazPhumse-1] = tempCalc;
                totalPresentation[pokazPhumse-1] = sumPresentationObsh;
                ui->total1->setStyleSheet("color: grey");
                ui->total1->setText(QString::number(double(tempCalc)/100, 'f', 2));
            }
            if(sumPresentationObsh % 10 == 5)
            {
                sumPresentationObsh /= 10;
                sumPresentationObsh += sumPresentationObsh % 2;
            }
            else
                sumPresentationObsh = qRound(sumPresentationObsh / 10.0);
            totalObj["tempCalc"] = tempCalc;
            totalObj["accuracyMin"] = totalObject["accuracyMin"];
            totalObj["accuracyMax"] = totalObject["accuracyMax"];
            totalObj["presentationMin"] = totalObject["presentationMin"];
            totalObj["presentationMax"] = totalObject["presentationMax"];
            qWarning()<<"totalSum = "<<totalSum[pokazPhumse];
            totalVistup[pokazPhumse] = tempCalc;
            totalPresentation[pokazPhumse] = sumPresentationObsh;
        }
        break;
    default:
        QJsonObject flagsObject = sqlReguest->flagsTotal(idperfomance);
        emit sendOcenFlags(flagsObject);
        QJsonValue jv;
        QJsonArray ja;
        QJsonObject subtree;
        sqlReguest->prynatGrades(idperfomance);
        ui->startFlags->setEnabled(true);
        ui->stopBtnFlags->setEnabled(false);
        for (int i=0; i<flagsObject.count(); i++) {
            jv = flagsObject.value("ocenki"+QString::number(i));
            if(jv.isArray()) {
                ja = jv.toArray();
                subtree = ja.at(0).toObject();
                if (subtree["ocenki_t"].toInt() == 1) btnFlags[subtree["ocenki_nomsud"].toInt()-1]->setStyleSheet("background-color: blue;");
                if (subtree["ocenki_p"].toInt() == 1) btnFlags[subtree["ocenki_nomsud"].toInt()-1]->setStyleSheet("background-color: red;");
            }
        }
        ui->lFlagsBlue->setText(QString::number(flagsObject["totalBlue"].toInt()));
        ui->lFlagsRed->setText(QString::number(flagsObject["totalRed"].toInt()));
        loadTablePerfomance();
        break;
    }
}

//Принимаем и выводим итоговые оценки за выступление
void MainWindow::on_prinat_clicked()
{
    startInt = 0;
    QMap<QString, QString> range;
    switch(pokazPhumse) {
    case 1:
        ui->total1->setStyleSheet("color: grey");
        ui->total1->setText(QString::number(double(tempCalc)/100, 'f', 2));
        break;
    case 2:
        for (int i = 1; i <= pokazPhumse; ++i) {
            sumObsh += totalSum[i];
            total += totalVistup[i];
            sumPresentationTotal += totalPresentation[i];
            qWarning()<<"sumObsh = "<<sumObsh;
        }
        totalObj["total"] = total;
        ui->total2->setStyleSheet("color: grey");
        ui->total->setStyleSheet("color: grey");
        ui->total2->setText(QString::number(double(tempCalc)/100, 'f', 2));
        total = (10 * total) / 2;
        if(total % 10 == 5)
        {
            total /= 10;
            total += total % 2;
        }
        else
            total = qRound(total / 10.0);
        qWarning()<<"total prinat = "<<total;
        ui->total->setText(QString::number(double(total)/100, 'f', 2));
        range["idvistuplenie_pred"] = QString::number(idperfomance-1);
        range["totalSecond"] = QString::number(tempCalc);
        range["total"] = QString::number(total);
        total = 0;
        break;
    }
    if(kolPhum == pokazPhumse) {
        range["idvistuplenie"] = QString::number(idperfomance);
        range["categories"] = kategoria;
        range["sumAccuracyObsh"] = QString::number(sumAccuracyObsh);
        range["sumPresentationObsh"] = QString::number(sumPresentationTotal/kolPhum);
        range["sumObsh"] = QString::number(sumObsh);
        range["totalFirst"] = QString::number(ui->total1->text().toDouble() * 100);
        range["nomer"] = QString::number(nomer);
        range["athlethe"] = sportsmen;
        range["krugNomer"] = QString::number(krugNomer);
        sqlReguest->insertRange(range);
        sumAccuracyObsh = 0;
        sumPresentationObsh = 0;
        sumPresentationTotal = 0;
        sumObsh = 0;
        for (int i = 1; i <= pokazPhumse; ++i) {
            totalSum[i] = 0;
            totalVistup[i] = 0;
            totalPresentation[i] = 0;
        }
    }
    ui->start->setEnabled(true);
    ui->prinat->setEnabled(false);
    ui->btn03->setEnabled(false);
    sqlReguest->prynatGrades(idperfomance);
    emit sendOcenSys(totalObj);
    loadTablePerfomance();
    ui->stopBtn->setEnabled(false);
    ui->btnTimer->setEnabled(false);
    tmrInt = 2;
    if (sqlReguest->countAthlethe(kategoria,krugNomer)/kolPhum == sqlReguest->countRang(kategoria,krugNomer)) {
        tmrInt = 0;
        ui->range->setEnabled(true);
        loadCategories();
    }
    startAutoTimer();
}

//Вкладка настройки выводим какие пхумсэ будут выполняться
void MainWindow::loadViewSettingsServer() {
    QSqlQueryModel *model = new QSqlQueryModel(this);
    model->setQuery("SELECT phumse_name FROM phumse where idphumse<17;");
    switch (settings->value("SETTINGS_SYST").toInt()) {
    case 1:
    case 2:
        ui->comboBoxSecond->hide();
        ui->comboBoxSecond->setModel(model);
        ui->comboBoxFirst->setModel(model);
        break;
    default:
        ui->comboBoxSecondFlags->hide();
        ui->comboBoxSecondFlags->setModel(model);
        ui->comboBoxFirstFlags->setModel(model);
        break;
    }
    phumNum = 1;
}

//Одно пхумсэ
void MainWindow::on_phum1_clicked()
{
    ui->comboBoxSecond->hide();
    phumNum = 1;
}

//Два пхумсэ
void MainWindow::on_phum2_clicked()
{
    ui->comboBoxSecond->show();
    phumNum = 2;
}

//Добавляем выступление в базу данных
void MainWindow::on_OK_clicked()
{
    QButtonGroup krug;
    QList<QRadioButton *> allKrugButton = ui->gbKrug->findChildren<QRadioButton *>();
    qWarning()<<"allKrugButton.size() = "<<allKrugButton.size();
    for(int i = 0; i < allKrugButton.size(); ++i)
    {
        krug.addButton(allKrugButton[i],i);
    }
    settingObj["str"] = ui->textEdit->toPlainText();
    settingObj["cat"] = ui->catEdit->text();
    settingObj["kolPhumse"] = phumNum;
    settingObj["krugNomerSetting"] = krug.checkedId()+1;
    switch (phumNum) {
        case 1:
        settingObj["phum1"] = ui->comboBoxFirst->currentIndex();
        break;
        case 2:
        settingObj["phum1"]  = ui->comboBoxFirst->currentIndex();
        settingObj["phum2"]  = ui->comboBoxSecond->currentIndex();
        break;
    }
    if(ui->catEdit->text().trimmed() != "") {
        sqlReguest->phumseServer(settingObj);
        loadTablePerfomance();
        QMessageBox::information(this, tr("Добавление"), tr("Выступление(я) добавлены!"));
    } else {
        QMessageBox::information(this, tr("Добавление"), tr("Категория пустая!"));
    }
//    if(sqlReguest->countAthlethe(ui->catEdit->text(), krugNomerSetting) != 0) {
//        connect(ui->OK, SIGNAL(clicked()), SLOT(showDialog()));
//    } else {
//        sqlReguest->phumseServer(settingObj);
//        loadTablePerfomance();
//        loadTablePerfomanceEnd();
//        QMessageBox::information(this, tr("Добавление"), tr("Выступление(я) добавлены!"));
//    }
}

void MainWindow::showDialog() {
    Dialog dlg(this);
    connect( &dlg, SIGNAL(applied()), SLOT(onApplied()));
    switch( dlg.exec() ) {
    case QDialog::Accepted:
        sqlReguest->phumseServer(settingObj);
        loadTablePerfomance();
        QMessageBox::information(this, tr("Добавление"), tr("Выступление(я) добавлены!"));
        ui->OK->setEnabled(true);
        break;
    case QDialog::Rejected:
        qDebug() << "Rejected";
        ui->OK->setEnabled(true);
        break;
    default:
        qDebug() << "Unexpected";
    }
}

void MainWindow::on_stopBtn_clicked()
{
    QJsonObject obj;
    startInt = 0;
    obj["command"] = 4;
    obj["idvitup"] = idperfomance;
    ui->start->setEnabled(true);
    ui->stopBtn->setEnabled(false);
    sqlReguest->stopVistup(obj);
    for(int j = 0; j < 10; j++) {
        tableWidget->item(0,j)->setBackground(Qt::white);
        tableWidgetEnd->item(0,j)->setBackground(Qt::white);
    }
    emit stopVistup(obj);
}

void MainWindow::on_range_clicked()
{
    emit readRange();
    ui->range->setEnabled(false);
    ui->start->setEnabled(true);
}

void MainWindow::on_btn03_clicked()
{
    minus03 += 1;
    ui->lMinus03->setText(QString::number(minus03));
    tempCalc -= 3;
}

//Отображаем таблицу выступлений
void MainWindow::loadTablePerfomance() {
    tableWidget->clear();
    QJsonObject athleteObject = sqlReguest->tablServerVist();
    QJsonValue jv;
    QJsonArray ja;
    QJsonObject subtree;
    QTableWidgetItem* head[10];
    QTableWidgetItem *item[10];

    for (int j=0;j<10;j++) {
        head[j] = new QTableWidgetItem();
        switch (j) {
        case 0:
            head[j]->setText("ID");
            break;
        case 1:
            head[j]->setText("Н");
            break;
        case 2:
            head[j]->setText("А");
            break;
        case 3:
            head[j]->setText("З");
            break;
        case 4:
            head[j]->setText("С");
            break;
        case 5:
            head[j]->setText("П");
            break;
        case 6:
            head[j]->setText("К");
            break;
        case 7:
            head[j]->setText("Спортсмен");
            break;
        case 8:
            head[j]->setText("Пхумсэ");
            break;
        case 9:
            head[j]->setText("Категория");
            break;
        }
        tableWidget->setHorizontalHeaderItem(j, head[j]);
    }
    jv = athleteObject.value("tablVis");
    if(jv.isArray()) {
        ja = jv.toArray();
        if(ja.count() > 0) tableWidget->setRowCount(ja.count());
        tableWidget->setColumnCount(10);
        tableWidget->setShowGrid(true);
        tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
        tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);
        for(int i=0; i<ja.count(); i++) {
        subtree = ja.at(i).toObject();
            for (int j=0;j<10;j++) {
                item[j] = new QTableWidgetItem();
                item[j]->setTextAlignment(Qt::AlignCenter);
                switch (j) {
                case 0:
                    item[j]->setText(QString::number(subtree.value("idvist").toInt()));
                    break;
                case 1:
                    item[j]->setText(QString::number(subtree.value("nomer").toInt()));
                    break;
                case 2:
                    item[j]->setText(QString::number(subtree.value("activno").toInt()));
                    break;
                case 3:
                    item[j]->setText(QString::number(subtree.value("zaver").toInt()));
                    break;
                case 4:
                    item[j]->setText(QString::number(subtree.value("sort").toInt()));
                    break;
                case 5:
                    item[j]->setText(QString::number(subtree.value("pokaz").toInt()));
                    break;
                case 6:
                    item[j]->setText(QString::number(subtree.value("krug").toInt()));
                    break;
                case 7:
                    item[j]->setText(subtree.value("sportsmen").toString());
                    break;
                case 8:
                    item[j]->setText(subtree.value("phumse").toString());
                    break;
                case 9:
                    item[j]->setText(subtree.value("kategoria").toString());
                    break;
                }
                tableWidget->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
                tableWidget->setItem(i,j, item[j]);
                if(subtree.value("activno").toInt() != 0) tableWidget->item(0,j)->setBackground(Qt::red);
            }
        }
    }

    switch (settings->value("SETTINGS_SYST").toInt()) {
    case 1:
    case 2:
        ui->vtableCutOfSystem->addWidget(tableWidget);
        ui->vTableWidgetEnd->addWidget(tableWidgetEnd);
        break;
    default:
        ui->vTableFlags->addWidget(tableWidget);
        ui->vTableWidgetEndFlags->addWidget(tableWidgetEnd);
//        if(athleteObject.count() > 0) connect(tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(doSomething(int,int)));
        break;
    }
    loadTablePerfomanceEnd();
}

void MainWindow::loadTablePerfomanceEnd() {
    tableWidgetEnd->clear();
    QJsonObject athleteObjectEnd = sqlReguest->tablServerVistEnd();
    QJsonValue jv;
    QJsonArray ja;
    QJsonObject subtree;

    QTableWidgetItem* headEnd[10];
    QTableWidgetItem *itemEnd[10];

    for (int j=0;j<10;j++) {
        headEnd[j] = new QTableWidgetItem();
        switch (j) {
        case 0:
            headEnd[j]->setText("ID");
            break;
        case 1:
            headEnd[j]->setText("Н");
            break;
        case 2:
            headEnd[j]->setText("А");
            break;
        case 3:
            headEnd[j]->setText("З");
            break;
        case 4:
            headEnd[j]->setText("С");
            break;
        case 5:
            headEnd[j]->setText("П");
            break;
        case 6:
            headEnd[j]->setText("К");
            break;
        case 7:
            headEnd[j]->setText("Спортсмен");
            break;
        case 8:
            headEnd[j]->setText("Пхумсэ");
            break;
        case 9:
            headEnd[j]->setText("Категория");
            break;
        }
        tableWidgetEnd->setHorizontalHeaderItem(j, headEnd[j]);
    }
    jv = athleteObjectEnd.value("tablVis");
    if(jv.isArray()) {
        ja = jv.toArray();
        if(ja.count() > 0) tableWidgetEnd->setRowCount(ja.count());
        tableWidgetEnd->setColumnCount(10);
        tableWidgetEnd->setShowGrid(true);
        tableWidgetEnd->setSelectionBehavior(QAbstractItemView::SelectRows);
        tableWidgetEnd->setSelectionMode(QAbstractItemView::SingleSelection);
        for(int i=0; i<ja.count(); i++) {
            subtree = ja.at(i).toObject();
            for (int j=0;j<10;j++) {
                itemEnd[j] = new QTableWidgetItem();
                itemEnd[j]->setTextAlignment(Qt::AlignCenter);
                switch (j) {
                case 0:
                    itemEnd[j]->setText(QString::number(subtree.value("idvist").toInt()));
                    break;
                case 1:
                    itemEnd[j]->setText(QString::number(subtree.value("nomer").toInt()));
                    break;
                case 2:
                    itemEnd[j]->setText(QString::number(subtree.value("activno").toInt()));
                    break;
                case 3:
                    itemEnd[j]->setText(QString::number(subtree.value("zaver").toInt()));
                    break;
                case 4:
                    itemEnd[j]->setText(QString::number(subtree.value("sort").toInt()));
                    break;
                case 5:
                    itemEnd[j]->setText(QString::number(subtree.value("pokaz").toInt()));
                    break;
                case 6:
                    itemEnd[j]->setText(QString::number(subtree.value("krug").toInt()));
                    break;
                case 7:
                    itemEnd[j]->setText(subtree.value("sportsmen").toString());
                    break;
                case 8:
                    itemEnd[j]->setText(subtree.value("phumse").toString());
                    break;
                case 9:
                    itemEnd[j]->setText(subtree.value("kategoria").toString());
                    break;
                }
                tableWidgetEnd->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
                tableWidgetEnd->setItem(i,j, itemEnd[j]);
                tableWidgetEnd->item(i,j)->setBackground(Qt::white);
                if(subtree.value("activno").toInt() != 0) tableWidgetEnd->item(i,j)->setBackground(Qt::red);
                if(subtree.value("zaver").toInt() != 0) tableWidgetEnd->item(i,j)->setBackground(Qt::green);
            }
        }
    }
    for (int i=0; i<athleteObjectEnd.count(); i++) {

    }
    switch (settings->value("SETTINGS_SYST").toInt()) {
    case 1:
    case 2:
        ui->vTableWidgetEnd->addWidget(tableWidgetEnd);
        break;
    default:
        ui->vTableWidgetEndFlags->addWidget(tableWidgetEnd);
//        if(athleteObject.count() > 0) connect(tableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(doSomething(int,int)));
        break;
    }
}

void MainWindow::startAutoTimer()
{
    if(ui->checkBox->isChecked()) {
        secondPerfomance = ui->spinBox->value();
        ui->lAutoTimer->setText(QString::number(secondPerfomance));
        tmr = new QTimer(this);
        tmr->setInterval(secondPerfomance);
        connect(tmr, SIGNAL(timeout()), this, SLOT(updateTime()));
        tmr->start(1000);
    }
}

void MainWindow::updateTime() {
    secondPerfomance--;
    ui->lAutoTimer->setText(QString::number(secondPerfomance));
    if(secondPerfomance < 0) {
        tmr->stop();
        delete tmr;
        switch (tmrInt) {
        case 1:
            on_prinat_clicked();
            break;
        case 2:
            on_start_clicked();
            break;
        }
    }
}

void MainWindow::on_stopTimer_clicked()
{
    tmrInt = 0;
    ui->checkBox->setChecked(false);
}

void MainWindow::on_btnTimer_clicked()
{
    if(tmrIntVistup == 0) {
        ui->lTimerPerfomance->show();
        timebegin = 90;
        ui->lTimerPerfomance->setText(secToMinSec(timebegin));
        tmrPerfomance = new QTimer(this);
        tmrPerfomance->setInterval(timebegin);
        connect(tmrPerfomance, SIGNAL(timeout()), this, SLOT(updateTimePerfomance()));
        tmrPerfomance->start(1000);
        tmrIntVistup = 1;
    } else {
        tmrPerfomance->stop();
        delete tmrPerfomance;
        tmrIntVistup = 0;
    }
}

void MainWindow::updateTimePerfomance() {
    timebegin--;
    ui->lTimerPerfomance->setText(secToMinSec(timebegin));
    if(!timebegin) {
        tmrPerfomance->stop();
        delete tmrPerfomance;
        tmrIntVistup = 0;
    }
}

void MainWindow::doSomething(int row, int column)
{
    QJsonObject obj;
    QString text;
    for(int i=0; i<9; i++) {
        text = tableWidget->item(row,i)->text();
        switch (i) {
        case 0:
        case 2:
        case 3:
        case 4:
        case 5:
        case 7:
            obj[QString::number(i)] = text;
            break;
        }
    }
    sqlReguest->updatePerfomance(obj);
    loadTablePerfomance();
}

void MainWindow::doSomethingEnd(int row, int column)
{
//    QJsonObject obj;
//    QString text;
//    for(int i=0; i<9; i++) {
//        text = tableWidgetEnd->item(row,i)->text();
//        switch (i) {
//        case 0:
//        case 2:
//        case 3:
//        case 4:
//        case 5:
//        case 7:
//            obj[QString::number(i)] = text;
//            break;
//        }
//    }
//    sqlReguest->updatePerfomance(obj);
//    loadTablePerfomance();
//    loadTablePerfomanceEnd();
}

void MainWindow::on_del_clicked()
{
    QJsonObject obj;
    try {
        int i= tableWidget->currentRow(); //строка
        if (!tableWidget->selectedItems().isEmpty())
        {
            obj["idvistuplenie"] = tableWidget->item(i,0)->text();
            sqlReguest->delVist(obj);
            loadTablePerfomance();
        }
    } catch (const std::exception& e) {

    }
}

void MainWindow::on_upd_clicked()
{
    loadTablePerfomance();
}

void MainWindow::on_update_clicked()
{
    loadTablePerfomance();
}

void MainWindow::on_delPerfomance_clicked()
{
    for(int i=0; i<tableWidgetEnd->rowCount(); i++) {
        sqlReguest->delPerfomance(tableWidgetEnd->item(i,0)->text().toInt());
    }
    loadCategories();
    loadTablePerfomance();
}

void MainWindow::flagsLoadView() {
    comboBox = new QComboBox(this);
    values = new QList<QPair<int,QString>>();
    model = new QComboBoxModel();
    groupsGrades[0] = ui->hJudgesFlags;
    groupsBtn[0].bvline = ui->vJudgesFlags;
    groupsBtn[0].bvline->addWidget(comboBox);
    groupsBtn[0].bgroup = new QButtonGroup(this);
    groupsBtn[0].bgroup->setProperty("lineNumber", 0);
    connect(groupsBtn[0].bgroup, SIGNAL(buttonClicked(QAbstractButton*)), this, SLOT(onButtonClicked(QAbstractButton*)));
    loadViewSettingsServer();
    for(int j=0; j<settings->value("SETTINGS_KSUD").toInt(); j++)
    {
        btnFlags[j] = new QPushButton();
        btnFlags[j]->setFixedSize(50,25);
        btnFlags[j]->setStyleSheet("background-color: green;");
        btnFlags[j]->setEnabled(false);
        btnFlags[j]->setText(QString::number(j+1));
        groupsGrades[0]->addWidget(btnFlags[j]);
        btn[0][j] = new QPushButton();
        btn[0][j]->setText(tr("Judges №") + QString::number(j+1));
        btn[0][j]->setProperty("styleclass", "judgesbtn");
        btn[0][j]->setProperty("value", j+1);
        groupsBtn[0].bvline->addWidget(btn[0][j]);
        groupsBtn[0].bgroup->addButton(btn[0][j]);
        groupsBtn[0].bvline->setEnabled(false);
   }
   loadTablePerfomance();
}

void MainWindow::on_OKFlags_clicked()
{
    QJsonObject obj;
    obj["str"] = ui->textEditFlags->toPlainText();
    obj["cat"] = ui->catEditFlags->text();
    obj["kolPhumse"] = phumNum;
    switch (phumNum) {
        case 1:
        obj["phum1"] = ui->comboBoxFirstFlags->currentText();
        break;
        case 2:
        obj["phum1"]  = ui->comboBoxFirstFlags->currentText();
        obj["phum2"]  = ui->comboBoxSecondFlags->currentText();
        break;
    }
    QMessageBox::information(this, tr("Спортсмены"), tr("Спортсмены добавлены"));
    sqlReguest->flagsServer(obj);
    loadTablePerfomance();
}

void MainWindow::on_phum2Flags_clicked()
{
    ui->comboBoxSecondFlags->show();
    phumNum = 2;
}

void MainWindow::on_phum1Flags_clicked()
{
    ui->comboBoxSecondFlags->hide();
    phumNum = 1;
}

void MainWindow::on_startFlags_clicked()
{
    countConnectJudges = 0;
    QJsonObject obj = sqlReguest->startVistup(settings->value("SETTINGS_SYST").toInt());
    if(obj.count() != 1) {
        ui->startFlags->setEnabled(false);
        obj["countJudges"] = settings->value("SETTINGS_KSUD").toInt();
        emit startPerfomance(obj);
        pokazPhumse = obj["pokaz"].toInt();
        idperfomance = obj["idvist"].toInt();
        kategoria = obj["kategoria"].toString();
        nomer = obj["nomer"].toInt();
        krugNomer = obj["krugNomer"].toInt();
        sportsmen = obj["sportsmen"].toString();
        ui->lFlagsBlue->setText("0");
        ui->lFlagsRed->setText("0");
        ui->lFlagsBlue->setStyleSheet("background-color: rgb(0, 87, 255); color: whire;");
        ui->lFlagsRed->setStyleSheet("background-color: rgb(255, 24, 0); color: white");
        loadTablePerfomance();
        emit sendDataFlags(obj);
        ui->prinatFlags->setEnabled(true);
        ui->stopBtnFlags->setEnabled(true);
        for(int j=0; j<settings->value("SETTINGS_KSUD").toInt(); j++)
        {
            btnFlags[j]->setStyleSheet("background-color: green;");
        }
    }
}

void MainWindow::on_prinatFlags_clicked()
{
    QJsonObject obj;
    obj["command"] = 6;
    emit waitPerfomance(obj);
    ui->prinatFlags->setEnabled(false);
}

void MainWindow::on_stopBtnFlags_clicked()
{
    QJsonObject obj;
    obj["command"] = 4;
    obj["idvitup"] = idperfomance;
    ui->startFlags->setEnabled(true);
    ui->stopBtnFlags->setEnabled(false);
    ui->prinatFlags->setEnabled(false);
    sqlReguest->stopVistup(obj);
    loadTablePerfomance();
    emit stopVistup(obj);
}

void MainWindow::closeEvent(QCloseEvent *event)
{
    ekran->close();
    ekranFlag->close();
}

void MainWindow::loadCategories()
{
    QJsonObject obj = sqlReguest->categoriesRang();
    QJsonValue jv;
    QJsonArray ja;
    QJsonObject subtree;
    ui->tableCategory->setRowCount(obj.count());
    ui->tableCategory->setColumnCount(1);
    ui->tableCategory->setShowGrid(true);
    ui->tableCategory->horizontalHeader()->setStretchLastSection(true);
    QTableWidgetItem* head = new QTableWidgetItem();
    head->setText("Категория");
    ui->tableCategory->setHorizontalHeaderItem(0, head);
    for (int i=0; i<obj.count(); i++) {
        jv = obj.value("categories"+QString::number(i+1));
        if(jv.isArray()) {
            ja = jv.toArray();
            subtree = ja.at(0).toObject();
            QTableWidgetItem* item = new QTableWidgetItem();
            item->setText(subtree.value("rang_category").toString());
            ui->tableCategory->setItem(i, 0, item);
        }
    }
    tabRange = new QTabWidget(this);
}

void MainWindow::on_tableCategory_itemClicked(QTableWidgetItem* itemCategory)
{
    QJsonObject rangeObject[3];
    QJsonObject krugObject = sqlReguest->krugCategory(itemCategory->text());
    QJsonValue jv;
    QJsonArray ja;
    QJsonValue jvKrug;
    QJsonArray jaKrug;
    QJsonObject subtree;
    QJsonObject subtreeKrug;
    QTableWidgetItem* head[5];
    QTableWidgetItem *item[5];
    tabRange->clear();
    jvKrug = krugObject.value("kort");
    if(jvKrug.isArray()) {
        jaKrug = jvKrug.toArray();
        tableRange[jaKrug.count()];
        for(int z=0; z<jaKrug.count(); z++) {
            subtreeKrug = jaKrug.at(z).toObject();
            rangeObject[z] = sqlReguest->selectRange(itemCategory->text(), subtreeKrug["nomer"].toInt());
            jv = rangeObject[z].value("rang");
            if(jv.isArray()) {
                ja = jv.toArray();
                tableRange[z] = new QTableWidget();
                if(ja.count() > 0) tableRange[z]->setRowCount(ja.count());
                tableRange[z]->setColumnCount(5);
                tableRange[z]->setShowGrid(true);
                tableRange[z]->setSelectionBehavior(QAbstractItemView::SelectRows);
                tableRange[z]->setSelectionMode(QAbstractItemView::SingleSelection);
                for (int j=0; j<ja.count(); j++) {
                    subtree = ja.at(j).toObject();
                    for(int x=0; x<5; x++) {
                        item[x] = new QTableWidgetItem();
                        head[x] = new QTableWidgetItem();
                        switch (x) {
                        case 0:
                            item[x]->setText(QString::number(j+1));
                            head[x]->setText("Место");
                            break;
                        case 1:
                            item[x]->setText(subtree["rang_athlethe"].toString());
                            head[x]->setText("Спортсмен");
                            break;
                        case 2:
                            item[x]->setText(subtree["rang_sumpres"].toString());
                            head[x]->setText("Презентация");
                            break;
                        case 3:
                            item[x]->setText(subtree["rang_sumobsh"].toString());
                            head[x]->setText("Сумма общая");
                            break;
                        case 4:
                            item[x]->setText(subtree["rang_tot"].toString());
                            head[x]->setText("Оценка");
                            break;
                        }
                        item[x]->setTextAlignment(Qt::AlignCenter);
                        tableRange[z]->setHorizontalHeaderItem(x, head[x]);
                        tableRange[z]->horizontalHeader()->resizeSections(QHeaderView::ResizeToContents);
                        tableRange[z]->setItem(j, x, item[x]);
                    }
                }
            }
            tabRange->addTab(tableRange[z], "Круг " + QString::number(z+1));
        }
    }
    ui->vRange->addWidget(tabRange);
}

